import React, { Component } from 'react'
import { Form, Input, Card, Icon, Select, Button, message } from 'antd';
import LinkButton from '../../components/link-button/link-button';
import { reqcategoryList, reqAddUpdateProduct } from '../../api/index'
import memoryUtils from '../../utils/memoryUtils';
import PicturesWall from './picture-wall'
import RichTextEditor from './richTextEditor'

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 15 },
};

const { TextArea } = Input;
const { Option } = Select;

class ProductAddUpdate extends Component {

    state={
      categoryNames:[]
    }

    constructor(props) {
      super(props);
      this.pwRef = React.createRef();
      this.richTextEditorRef = React.createRef()
    }

    // select 框 的选择
    handleChange(value) {
      // console.log(`selected ${value}`);
    }

    handleSubmit = e => {
      e.preventDefault();
      this.props.form.validateFields(async (err, values) => {
        if (!err) {
          // 获取表单数据
          const { categoryId, name, desc, price} = values
          const imgs = this.pwRef.current.getImgs()
          const detail = this.richTextEditorRef.current.getHtmlDetail()

          // 封装一个需要传送的product对象
          const product = {categoryId, name, desc, price, imgs, detail}
          if(this.isUpdate){
            product._id = this.product._id
          }
          
          // 发送请求
          const result = await reqAddUpdateProduct(product)
          if(result.status===0){
            message.success(`${this.isUpdate ? '修改' : '添加'}商品成功`)
            this.props.history.replace('/admin/product')
          }else{
            message.error(result.msg)
          }
        }
      });
    };
   

    // 自定义的price校验规则
    checkPrice = (rule, value, callback) => {
      if (!value) {
        callback('请输入商品价格');
      }else if(value <= 0){
        callback('商品价格必须大于0');
      }else{
        callback();
      }
    };

    UNSAFE_componentWillMount(){
      // 获取存储数据的商品
      this.product = memoryUtils.product
      this.isUpdate = !!(this.product._id)
    }


    // 获取分类数据
    async componentDidMount(){
      // console.log(this.pwRef.current.getImgs)
      // 获取分类列表，显示所有的分类
      const result = await reqcategoryList()
      let categoryNames
      if(result.status === 0){
        categoryNames = result.data
      }
      this.setState({categoryNames})
    }


    render() {
      
      const { getFieldDecorator } = this.props.form;
      const title = (
        <span>
          <LinkButton onClick={()=>this.props.history.goBack()}><Icon type="arrow-left" /></LinkButton>
          <span>{this.isUpdate?'修改商品':'添加商品'}</span>
        </span>
      )
        return (
          <Card title={title}>
          <Form {...formItemLayout} onSubmit={this.handleSubmit}>
              <Form.Item label="商品名称">
              {getFieldDecorator('name', {
                initialValue:this.product.name || '',
                rules: [
                  {
                    required: true,
                    message: '商品名称不能为空',
                  },
                ],
              })(<Input placeholder="请输入商品名称" />)}
            </Form.Item>
                <Form.Item label="商品描述">
                {getFieldDecorator('desc', {
                  initialValue:this.product.desc || '',
                  rules: [
                    {
                      required: true,
                      message: '商品描述不能为空',
                    },
                  ],
                })(<TextArea placeholder="请输入商品描述" />)}
              </Form.Item>
              <Form.Item label="商品价格">
              {getFieldDecorator('price', {
                initialValue:this.product.price || '',
                rules: [
                  {
                    required: true,
                    validator: this.checkPrice
                  },
                ],
              })(<Input type="number" addonAfter="RMB" />)}
            </Form.Item>
            <Form.Item label="商品分类">
            {getFieldDecorator('categoryId', {
              initialValue:this.product.categoryId || '',
              rules: [
                {
                  required: true,
                  message: '请选择商品分类',
                },
              ],
            })(<Select onChange={this.handleChange}>
            <Option value=''>未选择</Option>
            {this.state.categoryNames.map((item)=><Option value={item._id} key={item._id}>{item.name}</Option>)}
          </Select>)}
            </Form.Item>
            <Form.Item label="商品图片">
              {/* 修改商品时需要传一个对象给子组件渲染 */}
            <PicturesWall ref={this.pwRef} imgs={this.product.imgs}/>
            </Form.Item>
            <Form.Item label="商品详情" labelCol= {{ span: 3 }} wrapperCol={{span: 21}}>
              <RichTextEditor ref={this.richTextEditorRef} detail={this.product.detail}/>
            </Form.Item>
            <Button type="primary" htmlType="submit">提交</Button>
          </Form>
          </Card>
        )
    }
}
export default Form.create()(ProductAddUpdate)

/**添加表单
 * 1. 使用表单，向外暴露的不是原来的组件，需要暴露Form.create()(原来组件的名称)
 * 
 * 2. 页面布局
 * 
 * 指定form中所有item的布局
 * 方式一：
 * render() {
    const { getFieldDecorator } = this.props.form
    // 指定form中所有item的布局
    const formLayout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 8 }
    }
    return (
      <Card title={title}>
        <Form {...formLayout} onSubmit={this.handleSubmit}>
          <Item label="商品名称">
            {getFieldDecorator('name', {
              initialValue: '',
              rules: [
                { required: true, message: '必须输入商品名称!' }
              ],
            })(<Input placeholder="商品名称"/>)}
          </Item>
       </Form>
      </Card>
    )
 * 
 * 方式二：
 * render() {
    const { getFieldDecorator } = this.props.form
    return (
      <Card title={title}>
        <Form labelCol={{ span: 2 }} wrapperCol={{ span: 8 }} onSubmit={this.handleSubmit}>
          <Form.Item label="商品名称">
            {getFieldDecorator('name', {
              initialValue: '',
              rules: [
                { required: true, message: '必须输入商品名称!' }
              ],
            })(<Input placeholder="商品名称"/>)}
          </Form.Item>
       </Form>
      </Card>
    )
 * 
 * 
 * 3. 商品分类的数据渲染：
 * <Form.Item label="商品分类">
    //   此处的categoryId 为接口文档中对应的值
    {getFieldDecorator('categoryId', {
        initialValue: '',
        rules: [
        { required: true, message: '必须输入商品分类!' }
        ],
    })(
        <Select>
        <Option value=''>未选择</Option>
        {
            categorys.map(c => <Option value={c._id} key={c._id}>{c.name}</Option>)
        }
        </Select>
    )}
    </Form.Item>
 * 
 * 
 * 4. 商品价格的自定义校验
 * <Form.Item label="商品价格">
    {getFieldDecorator('price', {
        initialValue: product.price,
        rules: [
        { required: true, message: '必须输入价格!' },
        { validator: this.validatePrice }
        ],
    })(<Input type="number" placeholder="商品价格" addonAfter="元"/>)}
    </Form.Item>
 * 
  对价格进行自定义验证
    validatePrice = (rule, value, callback) => {
        if (value==='') {
        callback()
        } else if (value * 1 <=0) {
        callback('价格必须大于0')
        } else {
        callback()
        }
    }
 * 
 * 
 * 5. 收集数据，表单统一的验证
 *      5.1 绑定提交类型按钮
 *      <Button type="primary" htmlType="submit">提交</Button>
 * 
 *      5.2 同时form表单需要阻止默认提交的行为,后面需要发送ajax请求
 *      <Form onSubmit={this.handleSubmit}></Form>
 * 
 *      handleSubmit = (event) => {
            event.preventDefault()
        }
 * 
 *      5.3 进行表单验证
 * 
        handleSubmit = (event) => {
        // 阻止事件的默认行为(提交表单)
        event.preventDefault()

        // 进行统一的表单验证
        this.props.form.validateFields(async (err, values) => {
            if (!err) {
                const {name, desc, price, categoryId} = values
                console.log('发送请求', name, desc, price, categoryId)
            } 
        }
 * 
 * 
 * 
 * 
 */




 /**修改表单
  * 
  * 1. productHome 中 跳转到 ProductAddUpdate，productHome 跳转的同时需要将数据存储到内存中
  * productHome 中 绑定点击跳转的内容
  * <LinkButton
        onClick={() => {
        // 在内存中保存product
        memoryUtils.product = product
        this.props.history.push('/product/addupdate')
        }}
    >修改
    
    </LinkButton>
  * 
  * 2. ProductAddUpdate 在页面加载前需要判断内容中的product是否有值，如果有显示修改；如果没有显示新增
  *  componentWillMount () {
        this.product = memoryUtils.product
        // !!this.product._id ，将一个数据强制转换为布尔类型（做一个标识来显示新增还是修改）
        this.isUpdate = !!this.product._id
        }
  * 
  * 3. 取出值来判断
  * render() {
        const { categorys } = this.state
        const {isUpdate, product} = this

        const title = (
        <span>
            <LinkButton onClick={() => this.props.history.goBack()}>
            <Icon type="arrow-left" />
            </LinkButton>
            <span>{isUpdate ? '修改商品' : '添加商品'}</span>
        </span>
        )
    }
  * 
  * 4. 修改列表中渲染的默认值
  * <Form {...formLayout} onSubmit={this.handleSubmit}>
          <Form.Item label="商品名称">
            {getFieldDecorator('name', {
              initialValue: product.name,
            })()}
          </Form.Item>
          <Form.Item label="商品描述">
            {getFieldDecorator('desc', {
              initialValue: product.desc,
            })()}
          </Form.Item>
          <Form.Item label="商品价格">
            {getFieldDecorator('price', {
              initialValue: product.price,
            })()}
          </Form.Item>
          <Form.Item label="商品分类">
            {getFieldDecorator('categoryId', {
                // categoryId 取不到可能是undefined ，渲染的''对应的是未选择
              initialValue: product.categoryId || '',
            })(
              <Select>
                <Option value=''>未选择</Option>
              </Select>
            )}
          </Form.Item>
       </Form>
  * 
  * 
  * 5. 出现的bug：修改页面中直接浏览器刷新url，页面会变成添加页面，因为内存中的product为空
  * 
  * 
  */
